package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Order;
import com.draven.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ApiResponse createOrder(@RequestBody Order order) {
        try {
            // 设置下单时间
            order.setPayTime(new Date());
            
            // 创建订单
            Long orderId = orderService.createOrder(order);
            
            if (orderId != null) {
                return ApiResponse.success("订单创建成功", orderId);
            } else {
                return ApiResponse.error("订单创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("创建订单出错: " + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{id}")
    public ApiResponse getOrderDetail(@PathVariable Long id) {
        Order order = orderService.getById(id);
        if (order != null) {
            return ApiResponse.success(order);
        } else {
            return ApiResponse.error("订单不存在");
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel/{id}")
    public ApiResponse cancelOrder(@PathVariable Long id) {
        try {
            Order order = orderService.getById(id);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }
            
            // 只有待接单状态的订单可以取消
            if (order.getStatus() != 1) {
                return ApiResponse.error("只有待接单状态的订单可以取消");
            }
            
            // 更新订单状态为已取消
            order.setStatus(4);
            boolean success = orderService.updateById(order);
            
            if (success) {
                return ApiResponse.success("订单取消成功");
            } else {
                return ApiResponse.error("订单取消失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("取消订单出错: " + e.getMessage());
        }
    }
} 